package com.bwhx.eruler.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.bwhx.eruler.bean.Page;
import com.bwhx.eruler.bean.Staff;
import com.bwhx.eruler.bean.casdilly.CasdillyCustomer;
import com.bwhx.eruler.service.StaffService;
import com.bwhx.eruler.util.Constant;
import com.bwhx.eruler.util.MD5Utils;
import com.bwhx.eruler.util.StringUtils;

/**
 * 员工管理，销售员管理、库管管理
 * 
 * @author Cuilitang
 *
 */
@Controller
public class SellerController extends BaseController {

	@Autowired
	StaffService staffService;

	@ResponseBody
	// @RequestMapping(value = "/page.staffList.ashx")
	public Map staffList(Integer page, Integer rows, Staff s, @RequestBody String b) {
		log.info(b);
		// 每页的开始记录
		int start = (page - 1) * rows;
		Page p = new Page(start, rows, s);
		Map map = new HashMap();
		try {
			List<Staff> list = staffService.list(p);
			Integer count = staffService.count(s);
			log.info(list);
			log.info(count);

			map.put("total", count);// total键 存放总记录数，必须的
			map.put("rows", list);// rows键 存放每页记录 list
			for (Staff staff : list) {
				log.info(staff);
			}

		} catch (Exception e) {
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("status", "0");
		}

		return map;
	}

	@ResponseBody
	// @RequestMapping(value = "/page.saveOrUpdateStaff.ashx")
	public String saveOrUpdateStaff(Staff staff) {
		try {
			if (staff.getsId() == -1) {
				log.info("增加staff成功");
				log.info(staff);
				staff.setsId(null);
				staff.setsDeptId(1);
				staffService.insert(staff);
			} else {
				log.info("修改staff成功");
				log.info(staff);
				staff.setsDeptId(1);
				staffService.update(staff);

			}

		} catch (Exception e) {
			log.error(getTrace(e));
			return "fail";
		}

		return "success";
	}

	@ResponseBody
	// @RequestMapping(value = "/page.sellerListAll.ashx")
	public List<Staff> staffListAll() {
		List<Staff> list = new ArrayList<>();
		try {
			Staff staff = new Staff();
			staff.setsDeptId(1);
			Page page = new Page();
			page.setSearchObj(staff);
			list = staffService.list(page);

		} catch (Exception e) {
			log.error(getTrace(e));
		}

		return list;
	}

	@ResponseBody
	@RequestMapping(value = "/page.staffLogin.ashx")
	public Map get(HttpSession session, String username, String pwd, String code) throws IOException {
		/*
		 * Properties prop = new Properties();//属性集合对象 FileInputStream fis = new
		 * FileInputStream(this.getClass().getResource("/preference.properties").getPath
		 * ());//属性文件流 prop.load(fis);//将属性文件流装载到Properties对象中 fis.close();// 关闭流 String
		 * develop = prop.getProperty("develop"); if(develop.equals("1")){ Staff s =
		 * staffService.login("admin","123456"); session.setAttribute("staff", s); Map
		 * map = new HashMap<>(); map.put("msg", "success"); return map; }
		 * FileOutputStream fos = new
		 * FileOutputStream(this.getClass().getResource("/preference.properties").
		 * getPath()); // 将Properties集合保存到流中 prop.store(fos,
		 * "Copyright (c) Cuilitang 3Dcamega.com"); fos.close();// 关闭流
		 */ Map map = new HashMap<>();
		String tip = "";
		String piccode = (String) session.getAttribute("piccode");
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(pwd)
				|| StringUtils.isEmpty(code)/* || code.isEmpty() */) {
			tip = "请检查输入项是否为空";

			/*
			 * }else if(!piccode.equalsIgnoreCase(code)){
			 * 
			 * tip="验证码错误"; }else{
			 */

			/*
			 * log.info(username); log.info(pwd); log.info(code);
			 */
			log.info("==========" + "username:[" + username + "]；pwd:" + pwd + "；code:" + code + "==========");

			Staff s = staffService.login(username, pwd);
			if (s == null) {
				tip = "用户名或者密码错误";
			} else {
				if (s.getsStatus() == 1) {

					tip = "用户离职，账户冻结。";
				} else {
					session.setAttribute("staff", s);
					tip = "";
				}
			}

		}
		if ("".equals(tip)) {
			map.put("msg", "success");
		} else {
			map.put("msg", tip);
		}
		return map;
	}

	/*
	 * @ResponseBody
	 * 
	 * @RequestMapping(value = "/page.staffLogin.ashx") public Map get(HttpSession
	 * session,String username,String pwd,String code){ Map map = new HashMap<>();
	 * String tip="";
	 * 
	 * 
	 * Staff s = staffService.login("admin","bwhx*#06#");
	 * 
	 * session.setAttribute("staff", s);
	 * 
	 * if("".equals(tip)){ map.put("msg", "success"); return map; }else{
	 * map.put("msg", tip); return map;
	 * 
	 * }
	 * 
	 * }
	 */

	@ResponseBody
	@RequestMapping(value = "/page.everyone.changePwd.ashx")
	public String changePwd(HttpSession session, String pwd, String rePwd) {

		String responseText;
		Staff s = (Staff) session.getAttribute("staff");
		if ((!StringUtils.isEmpty(pwd)) && pwd.equals(rePwd) && pwd.length() >= 6) {
			s.setsPwd(MD5Utils.md5(pwd));
			staffService.update(s);
			responseText = "1";
		} else {
			responseText = "0";
		}
		return responseText;

	}

	@ResponseBody
	@RequestMapping(value = "/page.staffmenus.ashx")
	public ModelAndView staffmenus(@RequestParam String sId) {

		Staff staff = staffService.get(sId);
		ModelAndView modelAndView = new ModelAndView("/common/menuslist.jsp", "staff", staff);

		return modelAndView;

	}

	@ResponseBody
	@RequestMapping(value = "/page.staffAuthorization.ashx")
	public String staffAuthorization(@RequestBody String b) {

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		log.info(b);
		String decode = URLDecoder.decode(b);
		String[] split = decode.split("&");
		for (String string : split) {
			String[] split2 = string.split("=");
			if (split2.length == 2) {
				paramMap.put(split2[0], split2[1]);
			}

		}
		staffService.updatestaffAuthorization(paramMap);

		return "1";

	}

	@RequestMapping(value = "/page.logout.ashx")
	public String logout(HttpSession session) {
		session.removeAttribute("staff");
		session.invalidate();
		return "../../../index.jsp";

	}

	@RequestMapping("/page.getCaptcha.ashx")
	public void getCaptcha(HttpServletRequest request, HttpServletResponse response, String date) throws Exception {
		log.info("#######################生成数字和字母的验证码#######################" + date);
		// BufferedImage img = new BufferedImage(68, 22,BufferedImage.TYPE_INT_RGB);
		BufferedImage img = new BufferedImage(50, 22, BufferedImage.TYPE_INT_RGB);

		// 得到该图片的绘图对象

		Graphics g = img.getGraphics();

		Random r = new Random();

		Color c = new Color(200, 150, 255);

		g.setColor(c);

		// 填充整个图片的颜色

		g.fillRect(0, 0, 68, 22);

		// 向图片中输出数字和字母

		StringBuffer sb = new StringBuffer();

		char[] ch = "ABCDEFGHIJKLMNPQRSTUVWXYZ123456789!#$".toCharArray();

		int index, len = ch.length;

		for (int i = 0; i < 4; i++) {

			index = r.nextInt(len);

			g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt

			(255)));

			g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 15));
			// 输出的 字体和大小

			g.drawString("" + ch[index], (i * 10) + 3, 18);
			// 写什么数字，在图片 的什么位置画

			sb.append(ch[index]);

		}

		request.getSession().setAttribute("piccode", sb.toString());

		ImageIO.write(img, "JPG", response.getOutputStream());

	}

	/**
	 * 卡斯迪莱 员工量体师APP登录
	 * 
	 * @param session
	 * @param username
	 * @param pwd
	 * @param code
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/staffLogin.ashx")
	public Map<String, Object> staffLogin(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String username = (String) request.getAttribute("username");
		String pwd = (String) request.getAttribute("pwd");

		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(pwd)) {
			resultMap.put(Constant.MSG, "请检查输入项是否为空");
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);

		} else {

			Staff s = staffService.login(username, pwd);
			if (s == null) {
				resultMap.put(Constant.MSG, "用户名或者密码错误");
				resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			} else {

				resultMap.put(Constant.MSG, "登录成功");
				resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
				resultMap.put(Constant.DATA, s);

			}

		}
		return resultMap;

	}

	@ResponseBody
	@RequestMapping(value = "/staffChangePwd.ashx")
	public HashMap<String, Object> changePwd(HttpServletRequest request) {

		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Staff staff = new Staff();

		try {
			Integer sid = Integer.parseInt(request.getAttribute("sid").toString());
			String oldpwd = (String) request.getAttribute("oldpwd");
			String pwd = (String) request.getAttribute("pwd");
			String rePwd = (String) request.getAttribute("repwd");

			if ((!StringUtils.isEmpty(oldpwd))) {
				staff.setsId(sid);
				Staff staffBySID = staffService.get(sid);
				oldpwd = MD5Utils.md5(oldpwd);
				if (null != staffBySID && oldpwd.equals(staffBySID.getsPwd())) {
					if ((!StringUtils.isEmpty(pwd)) && pwd.equals(rePwd) && pwd.length() >= 6) {
						staff.setsId(sid);
						staff.setsPwd(MD5Utils.md5(pwd));
						staffService.changePwd(staff);

						resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
						resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
					} else {
						resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
						resultMap.put(Constant.MSG, "密码小于6位或者前后密码不一致");
					}
				} else {
					resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
					resultMap.put(Constant.MSG, "原密码错误，请重新输入");
				}

			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
				resultMap.put(Constant.MSG, "请输入原密码");
			}

		}

		catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}

		return resultMap;

	}

	@ResponseBody
	@RequestMapping(value = "/staffResetPwd.ashx")
	public HashMap<String, Object> staffResetPwd(HttpServletRequest request) {

		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Staff staff = new Staff();

		try {
			String phone = (String) request.getAttribute("phone");
			String pwd = (String) request.getAttribute("pwd");
			String rePwd = (String) request.getAttribute("repwd");

			if (StringUtils.isEmpty(phone) || ((!StringUtils.isEmpty(pwd)) && pwd.equals(rePwd) && pwd.length() >= 6)) {
				staff.setsPhone(phone);
				staff.setsPwd(MD5Utils.md5(pwd));
				Staff findByPhone = staffService.findByPhone(phone);
				if (findByPhone == null) {
					resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
					resultMap.put(Constant.MSG, "用户不存在");
				} else {
					staffService.changePwdByPhone(staff);

					resultMap.put(Constant.STATUS, Constant.STATUS_SUCCESS);
					resultMap.put(Constant.MSG, Constant.MSG_SUCCESS);
				}

			} else {
				resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
				resultMap.put(Constant.MSG, "手机号为空、密码小于6位、者前后密码不一致");
			}

		}

		catch (Exception e) {
			log.error(getTrace(e));
			resultMap.put(Constant.STATUS, Constant.STATUS_FAIL);
			resultMap.put(Constant.MSG, Constant.MSG_FAIL);
		}

		return resultMap;

	}

}
